const app = getApp();

Page({
  data: {
    addresses: []
  },

  onShow() {
    this.loadAddresses();
  },

  async loadAddresses() {
    try {
      const res = await app.request({
        url: '/address/',
        method: 'GET'
      });

      if (res.code === 200) {
        this.setData({
          addresses: res.data.map(address => ({
            ...address,
            fullAddress: `${address.province}${address.city}${address.district}${address.detail}`
          }))
        });
      }
    } catch (error) {
      console.error('获取地址列表失败', error);
      wx.showToast({
        title: '获取地址列表失败',
        icon: 'none'
      });
    }
  },

  handleAddAddress() {
    wx.navigateTo({
      url: '/pages/address/edit/edit'
    });
  },

  handleEditAddress(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/address/edit/edit?id=${id}`
    });
  },

  async handleDeleteAddress(e) {
    const { id } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const res = await app.request({
              url: `/address/${id}/`,
              method: 'DELETE'
            });

            if (res.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.loadAddresses();
            }
          } catch (error) {
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  async handleSetDefault(e) {
    const { id } = e.currentTarget.dataset;
    try {
      const res = await app.request({
        url: `/address/${id}/set_default/`,
        method: 'POST'
      });

      if (res.code === 200) {
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        });
        this.loadAddresses();
      }
    } catch (error) {
      wx.showToast({
        title: '设置失败',
        icon: 'none'
      });
    }
  }
}); 